package com.youlu.campus.wechat.service.impl;

import com.youlu.campus.activity.entity.ActivityLotteryPrize;
import com.youlu.campus.wechat.entity.SharingAccountInfo;
import com.youlu.campus.wechat.entity.SharingAccountInfoQueryVo;
import com.youlu.campus.wechat.entity.WechatProfitSharingLog;
import com.youlu.campus.wechat.repositories.SharingAccountInfoRepository;
import com.youlu.campus.wechat.service.SharingAccountInfoService;
import com.youlu.campus.wechat.service.WechatProfitSharingLogService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分账账户信息 Service 实现类
 */
@Service
public class SharingAccountInfoServiceImpl implements SharingAccountInfoService {

    @Autowired
    private SharingAccountInfoRepository sharingAccountInfoRepository;

    @Autowired
    private WechatProfitSharingLogService wechatBrandProfitSharingLogService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public SharingAccountInfo save(SharingAccountInfo sharingAccountInfo) {
        LocalDateTime now = LocalDateTime.now();
        if (StringUtils.isBlank(sharingAccountInfo.getId())) {
            sharingAccountInfo.setCreateTime(now);
        }
        sharingAccountInfo.setUpdateTime(now);
        return sharingAccountInfoRepository.save(sharingAccountInfo);
    }

    @Override
    public SharingAccountInfo findById(String id) {
        return sharingAccountInfoRepository.findById(id).orElse(null);
    }

    @Override
    public void deleteById(String id) {
        sharingAccountInfoRepository.deleteById(id);
    }

    @Override
    public Page<SharingAccountInfo> findByPage(SharingAccountInfoQueryVo paramVo) {
        Query query = new Query();
        if (StringUtils.isNotBlank(paramVo.getName())) {
            query.addCriteria(Criteria.where("name").regex(paramVo.getName()));
        }
        //统计总条数（分页需要先查总数）
        long total = mongoTemplate.count(query, ActivityLotteryPrize.class);
        //创建分页对象
        Pageable pageRequest = PageRequest.of(paramVo.getPage() - 1, paramVo.getPageSize());
        List<SharingAccountInfo> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            list = mongoTemplate.find(query, SharingAccountInfo.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }

    @Override
    public Page<SharingAccountInfo> findByMerchantId(SharingAccountInfoQueryVo paramVo) {
        String merchantId = paramVo.getMerchantId();
        long total = wechatBrandProfitSharingLogService.countByMerchantId(merchantId);
        //创建分页对象
        Pageable pageRequest = PageRequest.of(paramVo.getPage() - 1, paramVo.getPageSize());
        List<SharingAccountInfo> list = new ArrayList<>();
        if (total > 0) {
            List<WechatProfitSharingLog> logList = wechatBrandProfitSharingLogService.findByMerchantId(merchantId);
            logList = logList.stream().skip((paramVo.getPage() - 1) * paramVo.getPageSize()).limit(paramVo.getPageSize()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(logList)) {
                for (WechatProfitSharingLog sharingLog : logList) {
                    SharingAccountInfo accountInfo = findById(sharingLog.getAccountId());
                    if (accountInfo != null) {
                        list.add(accountInfo);
                    }
                }
            }
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }
}